package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Community;
import com.atguigu.entity.Dict;
import com.atguigu.service.CommunityService;
import com.atguigu.service.DictService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author: 翟文海
 * @Date: 2022/10/28/028 18:50
 * @Version: 1.0
 * @Description: TODO
 **/
@Controller
@RequestMapping("/community")
public class CommunityController extends BaseController {
    private static final String PAGE_INDEX = "community/index";
    private static final String PAGE_CREATE = "community/create";
    private static final String PAGE_SUCCESS = "common/successPage";
    private static final String PAGE_EDIT = "community/edit";
    private static final String LIST_INDEX = "redirect:/community";
    @Reference
    private DictService dictService;
    @Reference
    private CommunityService communityService;

    @RequestMapping
    public String index(Model model, @RequestParam Map<String, String> filters) {

        PageInfo<Community> page = communityService.findPage(filters);
        List<Dict> areaList = dictService.findByDictCode("beijing");
        model.addAttribute("page", page);
        model.addAttribute("areaList", areaList);
        if (filters.get("areaId") == null) {
            filters.put("areaId", "0");
        }
        if (filters.get("plateId") == null) {
            filters.put("plateId", "0");
        }
        model.addAttribute("filters", filters);
        return toPage(model, null, PAGE_INDEX);
    }

    @PostMapping("/save")
    public String save(Community community, Model model) {
        communityService.insert(community);

        return toPage(model, "新增小区成功", PAGE_SUCCESS);
    }

    @RequestMapping("/create")
    public String create(Model model) {
        List<Dict> dicts = dictService.findByDictCode("beijing");
        model.addAttribute("areaList", dicts);
        return toPage(model, null, PAGE_CREATE);
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, Model model) {
        Community community = communityService.getById(id);
        List<Dict> dicts = dictService.findByDictCode("beijing");
        model.addAttribute("community", community);
        model.addAttribute("areaList", dicts);
        return toPage(model, null, PAGE_EDIT);
    }

    @PostMapping("/update")
    public String update(Model model,Community community){
        communityService.update(community);
        return toPage(model,"更新小区成功",PAGE_SUCCESS);
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id) {
        communityService.delete(id);
        return LIST_INDEX;
    }


}
